#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
import time
import math
from aliyunsdkcore.client import AcsClient
from aliyunsdkalidns.request.v20150109 import DescribeDomainsRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models


def aliyun():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        try:
            get_aliyun_domain(account)
        except Exception as e:
            print(e)

def get_aliyun_domain(account):
    client = AcsClient(account.access_id,account.access_secret)
    request = DescribeDomainsRequest.DescribeDomainsRequest()
    request.set_accept_format('json')
    response = client.do_action_with_exception(request).decode('utf-8')
    response=json.loads(response)
    dns_list=response['Domains']['Domain']
    for domain in dns_list:
        domain_name=domain['DomainName']
        try:
            dnsobj=models.DNSDomain.objects.get(domain=domain_name,account=account)
        except Exception as e:
            dnsobj=models.DNSDomain(domain=domain_name,account=account)
            dnsobj.save()


def dnspod():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='dnspod').exclude(access_id__exact='')
    for account in account_list:
        try:
            get_dnspod_domain(account)
        except Exception as e:
            print(e)

def get_dnspod_domain(account):
    API="https://dnsapi.cn/Domain.List"
    id=account.access_id
    token=account.access_secret
    payload={}
    payload['login_token']='%s,%s' % (id,token)
    payload['format']='json'
    result=requests.post(API,data=payload).json()
    dns_list=result['domains']
    for domain in dns_list:
        domain_name=domain['name']
        if domain['status']=='enable' and domain['ext_status']=='':
            try:
                dnsobj=models.DNSDomain.objects.get(domain=domain_name,account=account)
            except Exception as e:
                dnsobj=models.DNSDomain(domain=domain_name,account=account)
                dnsobj.save()
        else:
            try:
                dnsobj=models.DNSDomain.objects.get(domain=domain_name,account=account)
                dnsobj.delete()
            except Exception as e:
                pass

def del_dns_domain():
    models.DNSDomain.objects.all().delete()

def main():
    del_dns_domain()
    aliyun()
    dnspod()

if __name__=='__main__':
    main()
